import { lineString, bezierSpline } from '@turf/turf';

/**
 * @description: 线标绘
 * @author: zhao_sk
 * @date: 2022-04-20 15:53:24
 */
export class Polyline {
	constructor(viewer) {
		this.viewer = viewer;
	}

	/**
	 * 添加线标绘
	 */
	async add(polylineData, callback) {
		const { id, polylineType, locationData, fillColor, lineWidth, pointSize, pointColor } =
			polylineData;
		if (this.viewer.getLayer(`VGEPolyline_${id}`)) {
			return console.error('id already registered');
		}
		let lineData = [];
		if (polylineType === 1) {
			//贝塞尔曲线
			let line = lineString(locationData);
			let curved = bezierSpline(line);
			lineData = [...curved.geometry.coordinates];
		} else {
			lineData = [...locationData];
		}
		this.viewer.addSource(`VGEPolyline_${id}`, {
			type: 'geojson',
			data: {
				type: 'FeatureCollection',
				features: [
					{
						type: 'Feature',
						geometry: {
							type: 'MultiLineString',
							coordinates: [lineData]
						}
					}
				]
			}
		});
		this.viewer.addSource(`VGEPolyline_${id}_cap`, {
			type: 'geojson',
			data: {
				type: 'FeatureCollection',
				features: [
					{
						type: 'Feature',
						geometry: {
							type: 'MultiLineString',
							coordinates: [locationData]
						}
					}
				]
			}
		});
		this.viewer.addLayer({
			id: `VGEPolyline_${id}`,
			type: 'line',
			source: `VGEPolyline_${id}`,
			paint: {
				'line-color': fillColor || 'rgba(11,223,141,1)',
				'line-width': +lineWidth || 3
			}
		});
		this.viewer.addLayer({
			id: `VGEPolyline_${id}_cap`,
			type: 'circle',
			source: `VGEPolyline_${id}_cap`,
			paint: {
				'circle-radius': +pointSize || 8,
				'circle-color': pointColor || '#06ceae'
			}
		});
	}

	/**
	 * 删除标签
	 */
	delete(id) {
		let sid = `VGEPolyline_${id}`;
		this.viewer.getLayer(sid) && this.viewer.removeLayer(sid);
		this.viewer.getLayer(`${sid}_cap`) && this.viewer.removeLayer(`${sid}_cap`);
		this.viewer.getSource(sid) && this.viewer.removeSource(sid);
		this.viewer.getSource(`${sid}_cap`) && this.viewer.removeSource(`${sid}_cap`);
		return true;
	}

	/**
	 * 清除标签
	 */
	clear() {
		this.viewer.getStyle().layers.forEach((item) => {
			if (item.id.includes('VGEPolyline_') && !item.id.includes('_cap')) {
				this.viewer.removeLayer(item.id);
				this.viewer.removeLayer(`${item.id}_cap`);
				this.viewer.removeSource(item.id);
				this.viewer.removeSource(`${item.id}_cap`);
			}
		});
		return true;
	}
}
